// home/04order/dialog.js
var co = require('../../js/common.js')
var ws = require('../../js/websocket.js')
var app = getApp()
var _this, _data, selected_uid, selected_state, orderOpt, getTimes = 0
Page({
   data: {
      order: {},
      creator: {},
      logs: [],
      striveMasterList: [],
      selectedMaster: '',
      offerViewShow: 0,
      myUid: ''
   },

   onLoad: function (opt) {
      _this = this
      _data = this.data
      this.setData({ myUid: app.aData.userInfo.unionid })
      wx.setNavigationBarTitle({ title: opt.order_id + '号订单详情' })
      orderOpt = opt
      _this.getOrderDetail()
   },
   //订单详情
   getOrderDetail: function () {
      co.getSelfApi('order/mg/getOrderDetail', orderOpt, function (res) {
         _this.setData({ order: res.data })
         _this.getUserInfo()
         _this.getStriveMasterList()
         if (getTimes) {
            co.toast('刷新成功')
         } else {
            getTimes++
         }
      })
   },
   //查看地图位置
   showMapLocation: function () {
      wx.openLocation({
         latitude: _data.order.latitude,
         longitude: _data.order.longitude,
         scale: '',
         name: '',
         address: '',
         success: function (res) {
            console.log('【跳转地图再跳导航】')
         },
         fail: function (res) { },
      })
   },
   //订单主人信息
   getUserInfo: function () {
      var param = { unionid: _data.order.creator_uid }
      co.getShareApi('user/mg/getuserinfo2', param, function (res) {
         _this.setData({ creator: res.data })
         _this.saveLogs(res.data)
      })
   },
   //检查去对话
   toDialog: function () {
      if (_data.selectedMaster != '') {
         co.modal('业主已选定师傅，不用对话了')
         return
      }

      if (_data.order.creator_uid == _data.myUid) {
         this.gotoDialog()
         return
      }

      if (this.isGotThisOrder()) {
         this.gotoDialog()
         return
      }
      co.modal('先争取此订单，才能进入业主对话哦！')
   },
   //去对话
   gotoDialog: function () {
      wx.navigateTo({ url: '/home/04order/dialog?order_id=' + _data.order.order_id })
   },
   //获取订单详情访问者
   getThisPageVisitors: function () {
      var param = { client: 'order:detail:' + _data.order.order_id }
      co.getSelfApi('user/Umg/getLogs', param, function (res) {
         _this.setData({ logs: res.data })
      })
   },
   //获取争取师傅列表
   getStriveMasterList: function () {
      var param = { order_id: _data.order.order_id }
      co.getSelfApi('order/Get/striveMasterList', param, function (res) {
         _this.setData({ striveMasterList: res.data })
         var list = res.data
         for (var i = 0; i < list.length; i++) {
            if (list[i].get_status == 1) {
               _this.setData({ selectedMaster: list[i] })
               console.log('【_data】', _data)
               return
               break
            }
         }
      })
   },
   //显示报价输入框
   showOrHideOfferView: function () {
      if (_data.myUid != _data.selectedMaster.unionid) {
         co.modal('等待选中的' + _data.selectedMaster.real_name + '师傅报价中…')
         return
      }
      this.setData({ offerViewShow: _data.offerViewShow ? 0 : 1 })
   },
   //报价
   offer: function (e) {
      var offer = e.detail.value.offer
      if (offer <= 0) {
         co.toast('报价金额不合法')
         return
      }
      var param = {
         order_id: _data.order.order_id,
         unionid: _data.myUid,
         offer: offer
      }
      co.getSelfApi('order/Get/offer', param, function (res) {
         co.modal('报价成功')
         //这里完成【4】步骤
         _this.updateOrderStatus({ target: { id: 4 } })
         //这上门费结账写法，还可以再严谨些
         if (_data.selectedMaster.offer < 1) {
            _this.checkout(_data.selectedMaster.unionid, 20)
         }
         _this.setData({
            offerViewShow: 0,
            selectedMaster: res.data
         })
      })
   },
   //结账
   checkout: function (uid, money) {
      var params = {
         unionid: uid,
         money: money,
      }
      co.getShareApi('user/Mg/balanceChange', params, function (res) {
         console.log('结账结果', res)
         if (uid == app.aData.userInfo.unionid) {
            app.aData.userInfo.balance = res.data.balance
            wx.setStorageSync('userInfo', app.aData.userInfo)
         }
      })
   },
   //争取订单
   get_order: function () {
      if (co.empty(app.aData.userInfo.user_id)) {
         this.toReg()
         return
      }

      if (_data.striveMasterList.length > 4) {
         co.modal('争取此订单师傅人数已满')
         return
      }

      if (this.isHasMasterSelected()) {
         co.modal('业主已选中师傅，不能争取了')
         return
      }

      if (_data.myUid == _data.order.creator_uid) {
         co.toast('不能接自己订单')
         return
      }

      if (this.isGotThisOrder()) {
         co.modal('您已争取此订单，不用再争取，等待业主选定')
         return
      }
      //未实名认证
      if (app.aData.userInfo.id_card_auth != 222) {
         this.toRealNameAuth()
         return
      }
      //未手机认证
      if (app.aData.userInfo.phone_auth != 1) {
         this.toPersonCenter()
         return
      }
      //未考试
      if (app.aData.userInfo.identity != 'master') {
         this.toExam()
         return
      }

      var keys = ['avatarUrl', 'unionid', 'openid', 'nickName', 'real_name', 'latitude', 'longitude']
      var param = co.addValueForKey({}, app.aData.userInfo, keys)
      param.order_id = _data.order.order_id
      param.order_latitude = _data.order.latitude
      param.order_longitude = _data.order.longitude
      co.getSelfApi('order/Get/setStatus', param, function (res) {
         app.playMp3('http://img.ls293.cc/repair/mp3/dingdanzhengqu_ok_master.mp3')
         co.modal('订单争取成功！等待业主选定', '祝您好运')
         //这里完成【2】流程步骤
         var list = _data.striveMasterList
         if (list.length == 0) {
            _this.updateOrderStatus({ target: { id: 2 } })
            _data.order.status = 2
            _this.setData({ order: _data.order })
         }
         list.push(param)
         _this.setData({ striveMasterList: list })
      })
   },
   //去注册的提示
   toReg: function () {
      wx.showModal({
         title: '温馨提示',
         content: '需要先允许授权注册，才能正常使用哦！',
         showCancel: true,
         cancelText: '取消',
         cancelColor: '',
         confirmText: '现在注册',
         confirmColor: '#f60',
         success: function (res) {
            if (res.confirm) {
               wx.navigateTo({ url: '/login/login' })
            }
         }
      })
   },
   //去实名认证的提示
   toRealNameAuth: function () {
      wx.showModal({
         title: '温馨提示',
         content: '实名认证后，才能接单哦！',
         showCancel: true,
         cancelText: '取消',
         cancelColor: '',
         confirmText: '现在认证',
         confirmColor: '#f60',
         success: function (res) {
            if (res.confirm) {
               var toUrl = '/pc/03apply/beMasterWorker?unionid='
               wx.navigateTo({ url: toUrl + _data.myUid })
            }
         },
         fail: function (res) { }
      })
   },
   //去认证手机的提示
   toPersonCenter: function () {
      wx.showModal({
         title: '温馨提示',
         content: '手机也要认证后，才能接单哦！',
         showCancel: true,
         cancelText: '取消',
         cancelColor: '',
         confirmText: '现在认证',
         confirmColor: '#f60',
         success: function (res) {
            if (res.confirm) {
               wx.switchTab({ url: '/pc/01personCenter/personCenter' })
            }
         },
         fail: function (res) { }
      })
   },
   //去考试的提示
   toExam: function () {
      wx.showModal({
         title: '温馨提示',
         content: '需要通过维修考试，才能接单哦！',
         showCancel: true,
         cancelText: '取消',
         cancelColor: '',
         confirmText: '现在考试',
         confirmColor: '#f60',
         success: function (res) {
            if (res.confirm) {
               wx.navigateTo({ url: '/master/exam/question' })
            }
         },
         fail: function (res) { }
      })
   },
   //检查是否有师傅被选中
   isHasMasterSelected: function () {
      var list = _data.striveMasterList
      for (var i = 0; i < list.length; i++) {
         var obj = list[i]
         if (obj.get_status == 1) {
            return true
            break
         }
      }
      return false
   },
   //检查是否已争取
   isGotThisOrder: function () {
      var list = _data.striveMasterList
      for (var i = 0; i < list.length; i++) {
         var obj = list[i]
         if (obj.unionid == _data.myUid) {
            return true
            break
         }
      }
      return false
   },
   //跳转到此师傅页面
   select: function (e) {
      var master = _data.striveMasterList[e.target.id]
      selected_uid = master.unionid
      selected_state = master.get_status
      if (_data.myUid != this.data.creator.unionid) {
         // wx.showToast({ title: '非业主点击' })
         return
      }
      this.setData({
         p: { x: e.detail.x + 10, y: e.detail.y - 60 },
         floatViewShow: this.data.floatViewShow ? 0 : 1
      })
   },
   //选定他上门检查
   selectedToDoor: function () {
      if (_data.selectedMaster != '') {
         co.modal('您已选师傅，不能再选了，谢谢')
         return
      }

      var param = {
         order_id: _data.order.order_id,
         unionid: selected_uid,
         get_status: 1
      }
      co.getSelfApi('order/Get/getStatusSet', param, function (res) {
         co.modal('您选中了“' + _this.getMasterName() + '”，等待他上门勘查')
         _this.updateOrderStatus({ target: { id: 3 } })
         _this.refreshMasterData()
         _this.setData({ floatViewShow: 0 })
      })
   },
   //刷新师傅数据
   refreshMasterData: function () {
      var list = _data.striveMasterList
      for (var i = 0; i < list.length; i++) {
         var obj = list[i]
         if (obj.unionid == selected_uid) {
            this.setData({ selectedMaster: list[i] })
            break
         }
      }
   },
   //跳转师傅信息
   toHisInfo: function (e) {
      wx.navigateTo({ url: '/pc/02user/masterInfo?unionid=' + selected_uid + '&get_status=' + selected_state })
      this.setData({ floatViewShow: 0 })
   },
   //获取师傅昵称
   getMasterName: function () {
      var list = _data.striveMasterList
      for (var i = 0; i < list.length; i++) {
         console.log('【selected_uid】' + selected_uid + '【list[' + i + '].unionid】', list[i].unionid)
         if (selected_uid == list[i].unionid) {
            return list[i].real_name
         }
      }
   },

   payVisitFee: function () {
      this.pay(1, 20, '支付维修上门费')
   },

   payRepairFee: function () {
      if (_data.order.creator_uid != _data.myUid) {
         co.modal('维修费等待业主支付，谢谢！')
         return
      }
      this.pay(5, _data.selectedMaster.offer, '支付维修费')
   },

   pay: function (status, money, _abstract) {
      //金额为上门费或维修费
      var param = {//e.detail.value
         openid: app.aData.userInfo.openid,
         appid: app.aData.app.appid,
         key: 'WqSeufzIsPDd4aGhGj97B3Il5g54bVDb',
         notify_url: 'http://api.ls293.cc/public/weixinpay/notify.php',
         mch_id: '1489661752',
         money: money,
         abstract: _abstract
      }

      co.getShareApi('weixin/pay/createParam', param, function (res) {
         res.data.success = function (result) {
            console.log('【调起支付成功res】', result)
            _this.sendSocketMsg(status)
            _this.savePay(status, money, _abstract)
         }
         res.data.fail = function (result) {
            console.log('【调起支付失败res】', result)
         }
         //调起微信支付
         wx.requestPayment(res.data)
      })
   },

   sendSocketMsg: function (status) {
      if (status == 5) {//付维修费
         app.playMp3('http://img.ls293.cc/repair/mp3/wenxintishi_owner.mp3')
         return
      }
      var order = _data.order
      order.type = 'notice'
      var msg = JSON.stringify(order)
      ws.sendSocketMsg(msg, function (res) {
         console.log('【发送后收到回调】', res)
      })
   },
   //保存支付
   savePay: function (status, money, _abstract) {

      this.updateOrderStatus({ target: { id: status } }, money)

      var params = {
         order_id: this.data.order.order_id,
         appid: app.aData.app.appid,
         org: 'repair',
         money: money,
         abstract: _abstract
      }
      var keys = ['avatarUrl', 'unionid', 'openid', 'nickName', 'real_name']
      params = co.addValueForKey(params, app.aData.userInfo, keys)
      co.getShareApi('finance/Fi/paySave', params, function (res) {
         console.log('支付保存结果', res)
      })
   },
   //更新订单状态
   updateOrderStatus: function (e, money) {//money如不为空，即为固定上门费
      //0:待付款，1:已付上门费，2:已有师傅争取，3:已选中师傅(互相可见电话)
      //4:师傅上门勘查报价，5已付报价款(并减上门费)，6已修好，7已验收（7天默认验收确认款到师傅账户）
      //这里完成【1】和【5】流程步聚
      var status = e.target.id
      var res = this.checkCanUserTap(status)
      if (status > 5) {
         co.modal(res.tips)
         if (status == 6) {
            app.playMp3('http://img.ls293.cc/repair/mp3/dingdanwancheng_master.mp3')
         }
         if (_data.order.status == 6) {
            app.playMp3('http://img.ls293.cc/repair/mp3/dingdanwancheng_owner.mp3')
         }
      }

      if (res.res != 'YES') {
         return
      }

      if (status == 1 || status == 5) {
         var param = {
            status: status,
            order_id: _data.order.order_id,
            payment: money
         }
      } else {
         var param = {
            status: status,
            order_id: _data.order.order_id
         }
      }
      co.getSelfApi('order/mg/updateStatus', param, function (res) {
         console.log('【_data】前', _data)
         _this.setData({ order: co.addValueForKey(_data.order, res.data, ['payment', 'status']) })
         console.log('【_data】后', _data)
      })
   },
   //
   checkCanUserTap: function (status) {
      switch (parseInt(status)) {
         case 9:
         case 6:
            if (_data.myUid != _data.selectedMaster.unionid)
               return { res: '', tips: '被选中维修的师傅才能点' }
            return { res: 'YES', tips: _data.selectedMaster.real_name + '师傅，祝贺您维修完成！' }
         case 7:
            if (_data.myUid != _data.order.creator_uid)
               return { res: '', tips: '业主才能点此验收确认' }
            //这里checkout结账还需要优化，遇到保修又会结账一次，要改
            this.checkout(_data.selectedMaster.unionid, _data.selectedMaster.offer - 20)
            return { res: 'YES', tips: '验收确认成功！感谢您对' + _data.selectedMaster.real_name + '师傅及平台的支持！' }
         case 8:
            if (_data.myUid != _data.order.creator_uid)
               return { res: '', tips: '业主才能呼叫保修' }
            return { res: 'YES', tips: '验收确认成功！感谢您对' + _data.selectedMaster.real_name + '师傅及平台的支持！' }
         default: return { res: 'YES', tips: '(未知提示)' }
      }
   },

   tips: function () {
      if (_data.myUid == _data.order.creator_uid) {
         co.modal('请选择您看中的师傅上门勘查维修问题')
      } else {
         co.modal('等待业主选定师傅中…')
      }
   },

   onReady: function () { },

   onShareAppMessage: function () { },

   saveLogs: function () {
      var keys = ['avatarUrl', 'unionid', 'openid', 'nickName']
      var log = co.addValueForKey({}, app.aData.userInfo, keys)
      log.client = 'order:detail:' + _data.order.order_id
      co.getSelfApi('user/Umg/saveLogs', log, function (res) {
         console.log('【日志保存结果】', res)
         _this.getThisPageVisitors()
      })
   },

   onUnload: function () {
      _data = null
      _this = null
      getTimes = 0
   }
})